import { makeAutoObservable, runInAction } from 'mobx';
import { RootStore } from './index';
// import { apiRequest } from '../utils/apiRequest';
import { UserSettings } from '../modules/UserModel';

export interface UserProfile {
  id: string;
  username: string;
  email: string;
  avatar?: string;
  phone?: string;
  createdAt: string;
  updatedAt: string;
}

export class UserStore {
  rootStore: RootStore;
  profile: UserProfile | null = null;
  settings: UserSettings = {
    notifications: true,
    darkMode: false,
    language: 'zh-CN',
    currency: 'CNY',
    autoBackup: false,
    reminderEnabled: true,
  };
  isLoading = false;
  error: string | null = null;

  constructor(rootStore: RootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this);
  }

  setProfile(profile: UserProfile | null) {
    this.profile = profile;
  }

  updateSettingsInStore(settings: Partial<UserSettings>) {
    this.settings = { ...this.settings, ...settings };
  }

  setLoading(loading: boolean) {
    this.isLoading = loading;
  }

  setError(error: string | null) {
    this.error = error;
  }

  async fetchProfile() {
    this.setLoading(true);
    this.setError(null);

    try {
      const response = await apiRequest('/user/profile');
      if (response.success) {
        runInAction(() => {
          this.setProfile(response.data.profile);
        });
      } else {
        runInAction(() => {
          this.setError(response.message || '获取用户信息失败');
        });
      }
    } catch (error) {
      runInAction(() => {
        this.setError('网络错误，请稍后重试');
      });
    } finally {
      this.setLoading(false);
    }
  }

  async updateProfile(data: Partial<UserProfile>) {
    this.setLoading(true);
    this.setError(null);

    try {
      const response = await apiRequest('/user/profile', {
        method: 'PUT',
        body: JSON.stringify(data),
      });

      if (response.success) {
        runInAction(() => {
          this.setProfile(response.data.profile);
        });
        return { success: true };
      } else {
        runInAction(() => {
          this.setError(response.message || '更新用户信息失败');
        });
        return { success: false, message: response.message };
      }
    } catch (error) {
      runInAction(() => {
        this.setError('网络错误，请稍后重试');
      });
      return { success: false, message: '网络错误' };
    } finally {
      this.setLoading(false);
    }
  }

  async updateSettings(newSettings: Partial<UserSettings>) {
    this.setLoading(true);
    this.setError(null);

    try {
      const response = await apiRequest('/user/settings', {
        method: 'PUT',
        body: JSON.stringify(newSettings),
      });

      if (response.success) {
        runInAction(() => {
          this.updateSettingsInStore(newSettings);
        });
        return { success: true };
      } else {
        runInAction(() => {
          this.setError(response.message || '更新设置失败');
        });
        return { success: false, message: response.message };
      }
    } catch (error) {
      runInAction(() => {
        this.setError('网络错误，请稍后重试');
      });
      return { success: false, message: '网络错误' };
    } finally {
      this.setLoading(false);
    }
  }

  async fetchSettings() {
    try {
      const response = await apiRequest('/user/settings');
      if (response.success) {
        runInAction(() => {
          this.updateSettingsInStore(response.data.settings);
        });
      }
    } catch (error) {
      console.error('Fetch settings error:', error);
    }
  }
}
